package com.hyfrogx.modules.zoom.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.log.LogEnum;
import com.hyfrogx.common.log.LogUtils;
import com.hyfrogx.common.utils.AppPushParam;
import com.hyfrogx.common.utils.Terminal;
import com.hyfrogx.config.ZoomConfig;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.operation.entity.HyAppPushEntity;
import com.hyfrogx.modules.zoom.entity.HyZoomMeeting;
import com.hyfrogx.modules.zoom.service.HyZoomMeetingService;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 实现Runnable接口的类
 *
 * @author Li9527 2017年10月31日11:28:56
 */
public class MyThreadUtils implements Runnable {
    // 封装对象
    @Autowired
    HyZoomMeeting hyZoomMeeting;

    private HyZoomMeetingService zoomMeetingService;

    @Autowired
    ZoomConfig zoomConfig;

    private static final String apiKey = "ypzTX051Q5a3-Bqv2kenLQ";

    private static final String apiSecret = "JTP2kWINanfZSJNZXIbHiqHJJpZ3K5PAZXbV";

    private Logger ZOOM_LOG = LogUtils.Logger(LogEnum.ZOOM_LOGS);

    public MyThreadUtils(HyZoomMeeting hyZoomMeeting, HyZoomMeetingService zoomMeetingService) {
        this.hyZoomMeeting = hyZoomMeeting;
        this.zoomMeetingService = zoomMeetingService;
    }

    public void run() {
        try {
            Thread.sleep(5000);
            // 将5s后的会议室包体查询出来
            HyZoomMeeting nwMetting = zoomMeetingService.getById(hyZoomMeeting.getId());
            // 如果是开启了一场新的会议
            if (!hyZoomMeeting.getZoomid().equals(nwMetting.getZoomid())) {
                // 接入参数
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("host_id", nwMetting.getHostid()));
                params.add(new BasicNameValuePair("api_key", apiKey));
                params.add(new BasicNameValuePair("api_secret", apiSecret));
                params.add(new BasicNameValuePair("id", nwMetting.getZoomid().toString()));
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpPost post = new HttpPost("https://www.zoomus.cn/v1/meeting/get");
                CloseableHttpResponse response = null;
                Integer flag = -1;
                // 加浏览器头防止被过滤
                post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
                post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
                response = httpclient.execute(post);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity httpEntity = response.getEntity();
                    if (null != httpEntity) {
                        String retSrc = EntityUtils.toString(httpEntity);
                        // 普通会议室获取回调进行数据持久化
                        JSONObject jsonObject = new JSONObject(retSrc);
                        // 会议室Id,每次开会都会重新创建被覆盖
                        flag = jsonObject.getInt("status");
                        System.out.println("当前状态为：-------" + flag);
                    }
                }
                if (flag == 0) {
                    nwMetting.setMeetstatus(0);
                    nwMetting.setIshavepsd(0);
                    nwMetting.setIscharge(0);
                    nwMetting.setPrice(0);
                    // 临时绑定展现id置空
                    nwMetting.setHymeetid(null);
                    // 密码
                    nwMetting.setPassword(null);
                    // 主题置空
                    nwMetting.setLocalname(null);
                    nwMetting.setTime(0);
                    Boolean result;
                    // 然后把不需要保留的数据置空
                    if (nwMetting.getId() != null) {
                        result = zoomMeetingService.updateById(nwMetting);
                    }
                }
            }
            // 开会总需要的时间秒数
            System.out.println("开会可以持续的时间秒数:----" + hyZoomMeeting.getTime());
            // 需要触发推送的时间秒数,结束前十分钟
            int needDoPushTime = hyZoomMeeting.getTime() - 300;
            for (int i = 0; i < hyZoomMeeting.getTime() - 5; i++) {
                // 线程休眠一秒
                Thread.sleep(1000);
                // 只有当前这个会议未结束,开会时间>10分钟,当前是倒计时十分钟.才推送
                if (hyZoomMeeting.getTime() > 300 && i == needDoPushTime) {
                    // 先通过会议id查询一下是否会议已终止<这个会议还在不在>,只有存在才调结束操作
                    HyZoomMeeting zoomMeeting = zoomMeetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("hymeetId", hyZoomMeeting.getHymeetid()));
                    if (zoomMeeting != null) {
                        // 当前时间秒
                        System.out.println("当前时间秒" + needDoPushTime + "执行任务----uid = " + nwMetting.getCurrentuid());
                        // 发送推送
                        HyAppPushEntity appPush = new HyAppPushEntity();
                        //推送对象设置为用户自定义
                        appPush.setAfterOpen(1);
                        //推送消息类型为参会提醒
                        appPush.setAppMessageType(4);
                        appPush.setTitle(" 友情提醒");
                        appPush.setText("您的体验时间即将结束，会议将在5分钟后自动结束");
                        appPush.setTicker("汉咏科技");
                        appPush.setType(AppPushParam.AppPushType.current);
                        appPush.setUid(nwMetting.getCurrentuid());
                        // 推送范围，0全部，1个体
                        appPush.setDisplayRange(1);
                        // 推送渠道：ios/andriod
                        appPush.setDisplayChannel(Terminal.DisplayChannel.all);
                        appPush.setCustomAfterOpen(FrogConstant.CustomAfterOpen.go_meet_end.getValue());
                        Boolean pushr = zoomMeetingService.doPush(appPush);
                        if (pushr) {
                            System.out.println("推送完毕");
                        } else {
                            System.out.println("推不了了");
                        }
                    }
                }
            }
            // 先通过会议id查询一下是否会议已终止<这个会议还在不在>,只有存在才调结束操作
            HyZoomMeeting zoomMeeting = zoomMeetingService.getOne(new QueryWrapper<HyZoomMeeting>().eq("hymeetId", hyZoomMeeting.getHymeetid()));
            if (zoomMeeting != null) {
                // for循环结束,开始业务操作
                zoomMeetingService.closeMeetZoom(zoomMeeting);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void start(HyZoomMeeting hyZoomMeeting, HyZoomMeetingService zoomMeetingService) {
        // 对象实例化
        MyThreadUtils hey = new MyThreadUtils(hyZoomMeeting, zoomMeetingService);
        // new 线程
        Thread t1 = new Thread(hey);
        // 启动线程
        t1.start();
    }

}